import { reqCartList, reqDeleteCartId, reqChangeCheckById } from '@/api'
import { getUUid } from '@/utils/index'
const state = {
    cartList: [],
    uuid_token: getUUid(),
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
};
const actions = {
    //获取购物车列表数据
    async getCartList(context) {
        let result = await reqCartList();
        if (result.code == 200) {
            context.commit('GETCARTLIST', result.data);
        }
    },
    async DeleteCartListBySkuId(context, skuId) {
        let result = await reqDeleteCartId(skuId);
        // console.log(result)
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    async changeCheckById(context, { skuId, isChecked }) {
        //改变一个check状态
        let result = await reqChangeCheckById(skuId, isChecked);
        // console.log(result)
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    deleteAllCkecked({ dispatch, getters }) {
        //删除所有选中的盒子
        let promises = [];
        getters.cartInfoList.forEach(element => {
            let promise = element.isChecked ? dispatch('DeleteCartListBySkuId', element.skuId) : '';
            promises.push(promise);
        });
        return Promise.all(promises);
    },
    updataAllchecked({ dispatch, getters }, checked) {
        //全选操作
        let cartInfoList = getters.cartInfoList;
        let promises = [];
        cartInfoList.forEach(element => {
            let promise = dispatch('changeCheckById', { skuId: element.skuId, isChecked: checked });
            promises.push(promise);
        });
        return Promise.all(promises)
    }
};
const getters = {
    cartInfoList(state) {
        return (state.cartList[0] || {}).cartInfoList || [];
    },
};
export default {
    state,
    mutations,
    actions,
    getters
}